package com.wjw.utils.prop;

import java.io.File;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @desc prop工具类
 * @author wjw
 * @date 2016年11月24日下午4:15:12
 */
public class PropKit {
	
	public static final String DEFAULT_ENCODING = "utf-8";
	
	private static Prop prop = null;
	private static final Map<String, Prop> map = new ConcurrentHashMap<String, Prop>();
	
	private PropKit() {}
	
	/** 加载用户的Properties属性文件*/
	public static Prop use(String fileName) {
		return use(fileName, DEFAULT_ENCODING);
	}
	/** 加载用户的Properties属性文件*/
	public static Prop use(String fileName, String encoding) {
		Prop result = map.get(fileName);
		if (result == null) {
			result = new Prop(fileName, encoding);
			map.put(fileName, result);
			if (PropKit.prop == null)
				PropKit.prop = result;
		}
		return result;
	}
	/** 加载用户的Properties属性文件*/
	public static Prop use(File file) {
		return use(file, DEFAULT_ENCODING);
	}
	/** 加载用户的Properties属性文件*/
	public static Prop use(File file, String encoding) {
		Prop result = map.get(file.getName());
		if (result == null) {
			result = new Prop(file, encoding);
			map.put(file.getName(), result);
			if (PropKit.prop == null)
				PropKit.prop = result;
		}
		return result;
	}
	
	/** 删除加载的Properties文件 */
	public static Prop useless(String fileName) {
		Prop previous = map.remove(fileName);
		if (PropKit.prop == previous)
			PropKit.prop = null;
		return previous;
	}
	
	/** 清空map加载的Properties文件 */
	public static void clear() {
		prop = null;
		map.clear();
	}
	
	/** 获取默认的prop文件  */
	public static Prop getProp() {
		if (prop == null)
			throw new IllegalStateException("Load propties file by invoking PropKit.use(String fileName) method first.");
		return prop;
	}
	
	/** 通过key获取map中的prop文件  */
	public static Prop getProp(String fileName) {
		return map.get(fileName);
	}
	
	/** 加载Properties文件返回map集合  */
    public static Map<String, String> mapUse(String resourceName) {
        Properties properties = PropKit.use(resourceName).getProperties();
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<?> e = properties.propertyNames();
        while( e.hasMoreElements()){
        	String key = (String)e.nextElement();
        	String value = properties.getProperty(key);
        	map.put(key, value);
        }
        return map;
    }
    
    public static void main(String[] args) {
    	Map<String, String> map = mapUse("base.properties");
    	for(Entry<String, String> entry : map.entrySet()){
    		System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
    	}
	}
}